﻿using Newtonsoft.Json;
using System.Windows;
using System.Windows.Documents;
using 充电桩上位机.Model.Authorize;
using 充电桩上位机.ViewModel;
using System.IO;
using System.Windows.Input;
using System.Text;
using System.Security.Cryptography.Xml;

namespace 充电桩上位机.View.Authorize
{
    /// <summary>
    /// Authorize.xaml 的交互逻辑
    /// </summary>
    public partial class Authorize : Window
    {
        public Authorize()
        {
            // 生成机器码
            InitializeComponent();
            string machineCode = LicenseGenerator.GenerateMachineCode();
            FTRandomString.Text = machineCode;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string _appStartupPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)!;
 
            byte[] key = Encoding.UTF8.GetBytes("1536518558527742");  // 16字节密钥
            byte[] iv = Encoding.UTF8.GetBytes("1396874257847166");   // 16字节IV

            //这里由工具生成
            //byte[] decrypted = ActivationKeyGenerator.AESEncrypt(FTRandomString.Text, key, iv);
            //FTSetLisence.Text = Convert.ToBase64String(decrypted);

            var _ = ActivationKeyGenerator.AESDecrypt(Convert.FromBase64String(FTSetLisence.Text), key, iv);

            //FTSetLisence.DataContext = activationKey;
            if (string.Equals(_, FTRandomString.Text))
            {
                //Environment.Exit(0);
                string jsonString = JsonConvert.SerializeObject(FTSetLisence.Text, Formatting.Indented);
                // 定义文件路径
                string filePath = new(Path.Combine
                                (_appStartupPath!, "Lisence", "PublicKey.json"));
                File.WriteAllText(filePath, jsonString);
                var uiMessageBox = new Wpf.Ui.Controls.MessageBox
                {
                    Title = "Benyi.",
                    Content = "Ulock OK. ",
                };
                var result = uiMessageBox.ShowDialogAsync();
                this.Close();
            }
            else
            {
                var uiMessageBox = new Wpf.Ui.Controls.MessageBox
                {
                    Title = "Benyi.",
                    Content = "Ulock Error. ",
                };
                var result = uiMessageBox.ShowDialogAsync();
                //this.Close();
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
    }
}
